package club.easin.config.db;

import club.easin.enums.DbEmHelper;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Configuration
public class DbConfig {

    @Bean(name="dbRouting")
    public DataSource dbRouting() throws IOException{
        InputStream in=this.getClass().getClassLoader().getResourceAsStream("db.properties");
        Properties pp=new Properties();
        pp.load(in);
        //创建每个库的datasource
        Map<Object,Object> targetDataSource=new HashMap<>(DbEmHelper.DbTypeEm.values().length);
        Arrays.stream(DbEmHelper.DbTypeEm.values()).forEach(dbType->{targetDataSource.put(dbType,getDataSource(pp, dbType));});

        Dbrouting dbrouting=new Dbrouting();
        dbrouting.setTargetDataSources(targetDataSource);

        return  dbrouting;
    }

    private DataSource getDataSource(Properties pp,DbEmHelper.DbTypeEm dbTypeEm){

        DruidDataSource builder=new DruidDataSource();
        builder.setDriverClassName(pp.getProperty("spring.datasource"+ dbTypeEm.getCode()+".driver-class-name"));
        builder.setUrl(pp.getProperty("spring.datasource"+ dbTypeEm.getCode()+".jdbc-url"));
        builder.setUsername(pp.getProperty("spring.datasource"+ dbTypeEm.getCode()+".username"));
        builder.setPassword(pp.getProperty("spring.datasource"+ dbTypeEm.getCode()+".password"));
        return builder;

    }
}
